package com.tywj.lib.core.common.util

import android.annotation.SuppressLint
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import java.text.SimpleDateFormat
import java.util.*


/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/7
 *     desc   : 时间工具类
 *     version: 1.0.0
 * </pre>
 */
object TimeUtil {

    // 默认格式
    const val PATTERN_DEFAULT = "yyyy-MM-dd HH:mm:ss"

    // 全部使用格式
    const val PATTERN_ALL = "yyyy-MM-dd HH:mm:ss:SSS"

    const val PATTERN_DAY_HH_MM = "yyyy-MM-dd HH:mm"

    //xxxx-xx-xx
    const val PATTERN_FORMAT = "yyyy-MM-dd"

    /**
     * 将时间戳转为时间字符串
     */
    fun millis2String(millis: Long, pattern: String = PATTERN_DEFAULT, timeZone: String = "GMT+8"): String {
        val dateTime = DateTime(millis, DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone)))
        return dateTime.toString(pattern)
    }

    /**
     * 将时间字符串转为时间戳
     */
    @SuppressLint("SimpleDateFormat")
    fun string2Millis(time: String, pattern: String = PATTERN_DEFAULT, timeZone: String = "GMT+8"): Long {
        val dateFormat = SimpleDateFormat(pattern)
        dateFormat.timeZone = TimeZone.getTimeZone(timeZone)
        return dateFormat.parse(time).time
    }

    /**
     * 获取当天的开始时间
     */
    fun getStartTimeOfDay(millis: Long, timeZone: String = "GMT+8"): Long {
        val curTimeZone = TimeZone.getTimeZone(timeZone)
        val calendar = Calendar.getInstance(curTimeZone)
        calendar.timeInMillis = millis
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        return calendar.timeInMillis
    }

    /**
     * 获取当天的结束时间
     */
    fun getEndTimeOfDay(millis: Long, timeZone: String = "GMT+8"): Long {
        val curTimeZone = TimeZone.getTimeZone(timeZone)
        val calendar = Calendar.getInstance(curTimeZone)
        calendar.timeInMillis = millis
        calendar.set(Calendar.HOUR_OF_DAY, 23)
        calendar.set(Calendar.MINUTE, 59)
        calendar.set(Calendar.SECOND, 59)
        calendar.set(Calendar.MILLISECOND, 999)
        return calendar.timeInMillis
    }
}